<!-- 群公告 -->
<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="addGroupVisible"
      width="800px"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :before-close="close"
    >
      <div>
        <el-form
          :model="formData"
          ref="form"
          :rules="rules"
          label-width="65px"
          :inline="false"
          size="small"
        >
          <el-form-item
            v-if="operateType === 'create'"
            label="群名称"
            prop="name"
          >
            <el-input
              v-model="formData.name"
              placeholder="请输入群名称"
              size="small"
              show-word-limit
              maxlength="50"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="select-box">
          <div class="left-search">
            <div class="search">
              <div class="title">请选择联系人：</div>
              <el-input
                placeholder="请输入内容"
                v-model="searchData"
                class="input-with-select"
                size="small"
                @keyup.enter.native="handleSearch"
              >
                <el-select
                  v-model="selectType"
                  slot="prepend"
                  size="small"
                  placeholder="请选择"
                >
                  <el-option label="联系人" value="1"></el-option>
                  <el-option label="部门" value="2"></el-option>
                </el-select>
                <el-button
                  size="small"
                  slot="append"
                  icon="el-icon-search"
                  @click="handleSearch"
                ></el-button>
              </el-input>
            </div>
            <div class="result">
              <template v-if="!searchData">
                <contact-tree
                  v-model="checkedUserList"
                  :operateType="operateType"
                ></contact-tree>
              </template>
              <template v-else-if="selectType == '2' && searchData">
                <contact-tree
                  :isRemote="true"
                  :operateType="operateType"
                  :departList="departList"
                  v-model="checkedUserList"
                ></contact-tree>
              </template>
              <div
                v-else-if="selectType == '1' && searchData"
                class="search-user-box"
              >
                <custom-checkbox-group
                  v-model="checkedUserList"
                  :userList="userList"
                  :operateType="operateType"
                ></custom-checkbox-group>
              </div>
            </div>
          </div>
          <div class="right-selected-user">
            <div class="title">已选择联系人：</div>
            <div class="selected-user-list">
              <el-tag
                v-for="(user, index) in checkedUserList"
                :key="index"
                closable
                size="medium"
                class="selected-tag-item"
                :disable-transitions="false"
                @close="handleCloseTag(user)"
              >
                <div class="tag-item">
                  <chat-avatar
                    :size="28"
                    :content="user.avatar ? user.avatar : user.name"
                  ></chat-avatar>
                  <span>{{ user.name }}({{ user.code }})</span>
                </div>
              </el-tag>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span>
          <el-button size="small" @click="close">取消</el-button>
          <el-button size="small" type="primary" @click="handleSubmit"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { createGroup, getUserList } from "@/api/user"
import { mapGetters, mapState } from "vuex"
import contactTree from "../common/contactTree.vue"
import customCheckboxGroup from "../common/customCheckboxGroup.vue"
import chatAvatar from "../common/avatar.vue"
import { getDeparmentTree } from "@/api/common"
import lockr from "lockr"

export default {
  name: "addGroupDialog",
  components: { contactTree, customCheckboxGroup, chatAvatar },
  props: {
    title: {
      type: String,
      default: "创建群聊"
    },
    operateType: {
      type: String,
      default: "create"
    }
  },
  data() {
    return {
      addGroupVisible: false,
      formData: {
        name: ""
      },
      checkedUserList: [],
      rules: {
        name: [{ required: true, message: "请输入群名称", trigger: "blur" }]
      },
      userList: [],
      departList: [],
      searchData: "",
      selectType: "1"
    }
  },
  computed: {
    ...mapGetters(["currentChatId"]),
    ...mapState(["currentChatInfo", "userInfo"])
  },

  mounted() {},

  methods: {
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const addMemberIds = this.checkedUserList.map((item) => item.id)
          this.operateType === "create"
            ? this.createNewGroup(addMemberIds)
            : this.$emit("submit", addMemberIds)
        }
      })
    },
    async createNewGroup(addMemberIds) {
      const res = await createGroup({
        masterId: this.userInfo.userId,
        name: this.formData.name,
        addMemberIds
      })
      if (res) {
        this.$message.success("创建成功")
        this.$store.dispatch("doSubscribe") //订阅
        this.$store.dispatch("getRecentChatList")
        this.close()
      }
    },
    close() {
      this.checkedUserList = []
      this.departList = []
      this.userList = []
      this.searchData = ""
      this.selectType = "1"
      this.formData = {
        name: ""
      }
      this.addGroupVisible = false
    },
    open() {
      this.addGroupVisible = true
    },
    handleSearch() {
      if (this.selectType == "1") {
        this.userByName()
      } else {
        this.userByRybm()
      }
    },
    handleCloseTag(user) {
      const index = this.checkedUserList.findIndex(
        (item) => item.code === user.code
      )
      if (index > -1) {
        this.checkedUserList.splice(index, 1)
      }
    },
    handleTreeCheck(data) {
      this.checkedUserList = data
    },
    async userByName() {
      const res = await getUserList({
        filter: {
          name: this.searchData
        }
      })
      this.userList = res.data.map(
        ({
          code,
          name,
          avatar,
          departmentName,
          departmentCode,
          onDutyPhone,
          phone,
          workPhone,
          motto,
          id
        }) => {
          return {
            code,
            name,
            avatar,
            departmentName,
            departmentCode,
            onDutyPhone,
            phone,
            workPhone,
            motto,
            id
          }
        }
      )
    },
    async userByRybm() {
      const res = await getDeparmentTree({
        filter: {
          name: this.searchData
        }
      })
      this.departList = res.data
    }
  },
  watch: {}
}
</script>
<style lang="less" scoped>
.select-box {
  display: flex;
  justify-content: space-between;
  .title {
    font-size: 14px;
    color: #000000;
    font-weight: 600;
    margin-bottom: 10px;
  }
  .left-search {
    width: 49%;
    .search {
      /deep/.el-icon-search {
        color: #333;
        font-size: 16px;
        font-weight: 500;
      }
      .el-select {
        width: 90px;
      }
    }

    .result {
      background: #ffffff;
      border: 1px solid #d5d5d5;
      border-radius: 4px;
      margin-top: 10px;
      height: 300px;
      overflow: auto;
      .search-user-box {
      }
    }
  }
  .right-selected-user {
    width: 49%;
    .selected-user-list {
      width: 100%;
      height: 342px;
      background: #ffffff;
      border: 1px solid #d5d5d5;
      border-radius: 4px;
      overflow: auto;
      .selected-tag-item {
        height: 42px;
        width: 200px;
        margin: 10px;
      }
      .tag-item {
        display: inline-flex;
        align-items: center;
        width: 90%;
        padding: 5px;
        > span {
          padding-left: 10px;
        }
      }
    }
  }
}
</style>
